package com.xue.mq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.xue.bean.SeckillMessage;

/**
 * Created by jiangyunxiong on 2018/5/29.
 */
@Service
public class MQSender {

    private static Logger log = LoggerFactory.getLogger(MQSender.class);

    @Autowired
    AmqpTemplate amqpTemplate;

//    public void send(Object message){
//        String msg = RedisService.beanToString(message);
//        log.info("send message:"+msg);
//        amqpTemplate.convertAndSend(MQConfig.QUEUE, message);
//    }

    public void sendTopic(Object message) {
		//String msg = RedisService.beanToString(message);
		//log.info("send topic message:"+msg);
		//amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE, "topic.key1", msg+"1");
		//amqpTemplate.convertAndSend(MQConfig.TOPIC_EXCHANGE, "topic.key2", msg+"2");
	}

	public void sendSeckillMessage(SeckillMessage message){
        String msg = beanToString(message);
        log.info("send message:"+msg);
        amqpTemplate.convertAndSend(MQConfig.QUEUE, msg);

    }
	/**
	 * 	获取返回值的发送信息。
	 * @param exchange
	 * @param routineKey
	 * @param content
	 * @return
	 */
	public Object sendAndReceive(String exchange, SeckillMessage message) {
		
		 String msg = beanToString(message);
		 
        Object obj = amqpTemplate.convertSendAndReceive(MQConfig.QUEUE, msg);
        //amqpTemplate.convertSendAndReceive(MQConfig.QUEUE, msg);
        return obj;
    }
	public static <T> String beanToString(T value) {
        if (value == null) {
            return null;
        }
        Class<?> clazz = value.getClass();
        if (clazz == int.class || clazz == Integer.class) {
            return String.valueOf(value);
        } else if (clazz == long.class || clazz == Long.class) {
            return String.valueOf(value);
        } else if (clazz == String.class) {
            return (String) value;
        } else {
            return JSON.toJSONString(value);
        }

    }
}
